package com.kaishengit.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.kaishengit.dao.MessageDao;
import com.kaishengit.pojo.Message;
import com.kaishengit.pojo.Project;
import com.kaishengit.pojo.User;
import com.kaishengit.util.DateUtil;
import com.kaishnegit.entity.Ajax;
import com.kaishnegit.entity.Ajax2;

@Service
@Transactional
public class MessageService {
	private MessageDao messageDao;
	
	public void save(Message message){
		messageDao.save(message);
	}
	
	public void save(Message message, User user, Project project) {
		message.setCreatetime(DateUtil.getDate());
		message.setUser(user);
		message.setProject(project);
		messageDao.save(message);
	}
	
	public void update(Message message){
		messageDao.update(message);
	}
	
	public void del(int id){
		messageDao.del(id);
	}
	
	public Message findById(int id){
		return messageDao.findById(id);
	}
	
	public List<Message> findAll(){
		return messageDao.findAll();
	}
	
	@Autowired
	public void setMessageDao(MessageDao messageDao) {
		this.messageDao = messageDao;
	}

	public List<Message> findByProject(Project project, int p) {
		return messageDao.findByProject(project,p);
	}

	public Ajax2 findAjaxProject(Project project, int p) {
		List<Ajax> ajaxs = new ArrayList<Ajax>();
		for(Message mes :messageDao.findByProject(project,p) ){
			Ajax ajax = new  Ajax();
			ajax.setId(mes.getId());
			ajax.setContent(mes.getContent());
			ajax.setCreatetime(mes.getCreatetime());
			ajax.setUsername(mes.getUser().getUsername());
			ajaxs.add(ajax);
		}
		int countnum = (int) messageDao.count(project);
		int count1 = (int) (countnum/5);
		if(countnum % 5 != 0){
			count1++;
		}
		Ajax2 ajax2 = new Ajax2();
		ajax2.setTotalpage(count1);
		ajax2.setAjaxList(ajaxs);
		return ajax2;
	}
}
